package com.xing.app.myutils.Utils;

import android.text.TextUtils;
import android.util.Log;

import com.xing.app.myutils.BuildConfig;

import java.io.File;
import java.io.FileFilter;
import java.io.FileWriter;
import java.util.Arrays;

public class LogUtil {

    private LogUtil() {
    }

    //日志存放路径
    public static String path = FileUtil.SD_Path;

    //默认是项目名称
    private static final String appName = BuildConfig.projectName;

    private static boolean isPrint = true;//默认开启日志打印

    private static final long maxsize = 204800;// 200KB 就换文件
    private static final long timeLimit = 7776000000L;// 90天

    /**
     * 使用前应该先初始化
     *
     * @param logPath 日志存放路径，传入空值表示默认路径
     */
    public static void init(String logPath) {
        if (TextUtils.isEmpty(logPath)) {
            LogUtil.path = path + File.separator + appName;
        } else {
            LogUtil.path = logPath;
        }

        File file = new File(path);
        if (!file.exists() || !file.isDirectory()) {
            file.mkdirs();
        }
    }

    /**
     * 是否开启日志打印，默认是打印的
     */
    public static void setIsPrint(boolean b) {
        isPrint = b;
    }

    /**
     * 将日志写入本地
     */
    private static void writeLog(final String tag, final String s) {
        if (!isPrint) return;

        new Thread(new Runnable() {
            @Override
            public void run() {
                FileWriter fw = null;
                try {

                    String name = getLogFileName();

                    File file = new File(name.substring(0, name.lastIndexOf("/")),
                            name.substring(name.lastIndexOf("/") + 1));

                    if (!file.exists()) {
                        file.createNewFile();
                    }

                    String time = DateUtil.getYYYYMMDDHHMMSS() + " ";
                    fw = new FileWriter(file, true);

                    fw.write(time + "[" + tag + "]:" + s + "\n");

                    fw.flush();

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (fw != null) {
                            fw.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    public static void d(String s) {
        String className = Thread.currentThread().getStackTrace()[3].getClassName();
        className = className.substring(className.lastIndexOf(".") + 1);
        Log.d(className, s);
        writeLog("DEBUG" + className, s);
    }

    public static void e(String s) {
        String className = Thread.currentThread().getStackTrace()[3].getClassName();
        className = className.substring(className.lastIndexOf(".") + 1);
        Log.e(className, s);
        writeLog("ERROR" + className, s);
    }

    public static void i(String s) {
        String className = Thread.currentThread().getStackTrace()[3].getClassName();
        className = className.substring(className.lastIndexOf(".") + 1);
        Log.i(className, s);
        writeLog("INFO" + className, s);
    }

    public static void w(String s) {
        String className = Thread.currentThread().getStackTrace()[3].getClassName();
        className = className.substring(className.lastIndexOf(".") + 1);
        Log.w(className, s);
        writeLog("WARRING" + className, s);
    }

    public static void v(String s) {
        String className = Thread.currentThread().getStackTrace()[3].getClassName();
        className = className.substring(className.lastIndexOf(".") + 1);
        Log.v(className, s);
        writeLog("VERBOSE" + className, s);
    }

    /**
     * @return 日志的文件名
     */
    private static String getLogFileName() {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }

        FileFilter fileFilter = new FileFilter() {
            long nowTime = System.currentTimeMillis();

            @Override
            public boolean accept(File file) {
                if (file.getName().endsWith(".log")) {
                    if (file.lastModified() < nowTime - timeLimit) {
                        file.delete();
                        return false;
                    } else {
                        return file.length() < maxsize;
                    }
                }
                return false;
            }
        };

        File[] files = file.listFiles(fileFilter);

        if (files == null || files.length == 0) {
            String fileTime = DateUtil.convert2String(System.currentTimeMillis());
            fileTime = fileTime.replaceAll("-", "");
            fileTime = fileTime.replaceAll(":", "");
            fileTime = fileTime.replaceAll(" ", "");

            return file.getAbsolutePath() + "/" + fileTime + ".log";
        } else {
            Arrays.sort(files);
            return files[0].getAbsolutePath();
        }
    }

}
